#-*- coding: utf-8 -*-#
__author__ = 'yangq'

from tornado import gen
from appcommon.appinstance import mysql_app_pool


@gen.coroutine
def get_news_list(type, pubtime, page_count):
    sql = (
        "select id as news_id, title,create_time as pubtime,content from app_news_info "
        "where type={} and is_using=1 {} order by pubtime desc limit {}"
    )
    param = " and create_time < {}".format(pubtime) if pubtime else ""
    info = yield mysql_app_pool.get_all(sql.format(type, param, page_count), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def get_news_content(news_id):
    sql = (
        "select a.id as news_id, a.title,a.create_time as pubtime, a.content as content,b.cnt as view_cnt "
        "from app_news_info a,app_view_cnt b where a.id = {} and a.id=b.view_id and b.type=0"
    )
    info = yield mysql_app_pool.get_all(sql.format(news_id), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def update_view_cnt(news_id):
    try:
        sql = "select 1 from app_view_cnt where view_id = {} and type=0"
        info = yield mysql_app_pool.get_one(sql.format(news_id), cursor='dict')
        if info:
            sql_update = "update app_view_cnt set cnt=cnt+1 where view_id={} and type=0"
            yield mysql_app_pool.update(sql_update.format(news_id))
        else:
            sql_insert = "insert into app_view_cnt (view_id,cnt,type) values ({}, 1, 0)"
            yield mysql_app_pool.update(sql_insert.format(news_id))
        res = True
    except Exception, e:
        print e
        res = False
    raise gen.Return(res)


@gen.coroutine
def get_news_list_with_id(news_id_list):
    list_str = ""
    for item in news_id_list:
        list_str += ','+str(item)
    list_str = list_str[1:]
    sql = (
        "select id as news_id, title,create_time as pubtime from app_news_info "
        "where id in ({})"
    )
    info = yield mysql_app_pool.get_all(sql.format(list_str), cursor='dict')
    raise gen.Return(info)